import React, {PureComponent, useEffect, useState} from 'react';
import {
  View,
  TouchableOpacity,
  Modal,
  Text,
  DeviceEventEmitter,
  TouchableWithoutFeedback,
  Image,
  Linking,
} from 'react-native';
import {useWalletConnect} from '@walletconnect/react-native-dapp';
import {Colors} from '../styles/common';
import {
  TextButton,
  LinearButton,
  LinearBoardButton,
} from '../components/Button';
import StorageManager, {METAMASK_ADDRESS} from '../storage';
import store from '../redux/store/index';
export default function WalletConnect({
  resultCall,
  tx,
  visible,
  onPressBackground,
}) {
  const connector = useWalletConnect();

  let [checked, setChecked] = useState(false);

  let [showSign, setShowSign] = useState(true);

  useEffect(() => {
    console.log('页面状态改变', visible);
    if (visible) {
      StorageManager.load(METAMASK_ADDRESS).then((res) => {
        console.log('存储的metamask数据' + res);
        if (JSON.parse(res)?.hiddenAlert) {
          signinTransaction();
        }

        setChecked(JSON.parse(res)?.hiddenAlert);
      });
    }
  }, [visible]);

  useEffect(() => {
    let linkingListen = Linking.addEventListener('url', (event) => {
      handleOpenURL(event.url);
    });

    return () => {
      linkingListen && linkingListen.remove();
    };
  }, []);

  handleOpenURL = async (url) => {
    url = decodeURIComponent(url);

    console.log('---跳转的url为' + url);
    try {
      let paramsPart = url.split('?')[1];
      let params = paramsPart.split('&') || [];
      let param = {};
      params.map((item) => {
        let key = item.split('=')[0];
        let value = item.split('=')[1];
        param[key] = value;
      });
      console.log(param);
      if (param.chain) {
        let res = JSON.parse(param.chain);
        console.log('切换的chain信息为', JSON.stringify(res, null, 2));
        console.log(connector.chainId);

        setShowSign(false);

        connector.updateSession({
          chainId: parseInt(res.chainId, 16),
          networkId: parseInt(res.chainId, 16),
          accounts: connector.accounts,
        });

        console.log('切换后');
        console.log(connector.chainId);
        setShowSign(true);
      }
    } catch (err) {
      //   this._showAlert(err);
    }
  };

  const connectWallet = async () => {
    if (connector.connected) {
      return;
    }
  };

  const signinTransaction = async () => {
    console.log(tx);

    if (checked) {
      //保存提示，每次更换钱包地址的时候重置
      StorageManager.load(METAMASK_ADDRESS).then((res) => {
        StorageManager.save(
          METAMASK_ADDRESS,
          JSON.stringify({
            ...JSON.parse(res),
            hiddenAlert: true,
          }),
        );
      });
    }

    if (!connector.connected) {
      console.log('非连接状态，退出');
      return;
    }

    /**
     
export interface ICallTxData {
  type?: string;
  to?: string;
  value?: number | string;
  gas?: number | string;
  gasLimit?: number | string;
  gasPrice?: number | string;
  nonce?: number | string;
  data?: string;
}

export interface ITxData extends ICallTxData {
  from: string;
}
     */
    connector
      .sendTransaction(tx)
      .then((res) => {
        console.log('发送成功');
        console.log(res);
        resultCall && resultCall(res);
      })
      .catch((err) => {
        console.log(err);
        console.log('发送失败' + err?.message);
        resultCall && resultCall(null, err?.message || err + '');
      });
  };

  const killSession = async () => {
    console.log(connector);

    connector
      .killSession()
      .then((res) => {
        console.log('关闭成功' + res);
      })
      .catch((err) => {
        console.log('关闭失败' + err);
      });
  };

  const switchNetwork = () => {
    Linking.openURL(
      'https://metamask.app.link/dapp/metamask.signin.art/select_chain.html?chain=' +
        store.getState().Chain.config.chainId,
    );
  };

  return (
    <Modal animationType="fade" transparent visible={visible}>
      <View
        style={{
          justifyContent: 'flex-end',
          flex: 1,
          backgroundColor: 'rgba(151,151,151,0.5)',
        }}>
        <TouchableWithoutFeedback onPress={onPressBackground}>
          <View
            style={{
              flex: 1,
              width: '100%',
            }}></View>
        </TouchableWithoutFeedback>
        <View
          style={{
            backgroundColor: 'rgba(255,255,255,0.95)',
            width: '100%',
            alignItems: 'flex-start',
            padding: 20,
            position: 'absolute',
            bottom: 0,
            left: 0,
            borderTopLeftRadius: 15,
            borderTopRightRadius: 15,
          }}>
          <Text
            style={{
              color: Colors.fontPurpleColorLight,
              fontWeight: 'bold',
              marginLeft: 20,
              marginTop: 20,
              marginBottom: 0,
              fontSize: 16,
            }}>
            Makesure your wallet is bsc network
          </Text>
          <Text
            style={{
              color: Colors.fontBlackColor_31,
              marginLeft: 20,
              marginTop: 20,
              marginBottom: 20,
              fontSize: 14,
            }}>
            Note that it takes a few seconds to open the transaction window page
            after opening the wallet. Please wait!
          </Text>
          <View
            style={{
              width: '100%',
              marginBottom: 0,
              flexDirection: 'row',
              justifyContent: 'flex-end',
              alignItems: 'center',
              paddingRight: 20,
              paddingLeft: 20,
              // backgroundColor: 'red',
            }}>
            <TouchableOpacity
              style={{flexDirection: 'row', alignItems: 'center'}}
              activeOpacity={0.8}
              onPress={() => {
                setChecked(!checked);
              }}>
              <Text
                numberOfLines={1}
                style={{color: Colors.fontPurpleColorLight, marginRight: 4}}>
                Auto Sign
              </Text>
              <Image
                style={{width: 20, height: 20, marginRight: 10}}
                source={
                  checked
                    ? require('../assets/auction/p_checkbox.png')
                    : require('../assets/auction/p_checkbox-empty.png')
                }
              />
            </TouchableOpacity>
          </View>
          <View style={{width: '100%', marginBottom: 30}}>
            {showSign &&
            connector.chainId == store.getState().Chain.config.chainId ? (
              <LinearButton
                buttonStyle={{
                  flex: 1,
                  marginLeft: 30,
                  marginRight: 30,
                }}
                onPress={signinTransaction}
                text={'Sign Transaction'}></LinearButton>
            ) : (
              <LinearButton
                buttonStyle={{
                  flex: 1,
                  marginLeft: 30,
                  marginRight: 30,
                }}
                onPress={switchNetwork}
                text={'Switch Bsc Network'}></LinearButton>
            )}
          </View>
        </View>
      </View>
    </Modal>
  );
}
